<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function ajax(add) {
            //返回一个promise
            return new Promise((resolve, reject) => {
                //1、创建ajax对象
                var xhr = new XMLHttpRequest();
                console.log('xhr ==> ', xhr);
                console.log('创建xhr对象 xhr.readyState ==> ', xhr.readyState);

                //2、监听ajax对象状态的变化
                xhr.onreadystatechange = function () {
                    // console.log('this ==> ', this);
                    console.log('监听 this.readyState ==> ', this.readyState);

                    //获取服务器成功响应的数据
                    if (this.readyState === 4 && this.status === 200) {
                        //ajax状态为 4 且 http状态码为 200

                        //获取响应的数据
                        resolve(this.response);
                    }
                };

                //API: 接口
                //3、建立服务器(接口地址)连接
                let params = '';
                add.type = add.type.toLowerCase();

                if (add.data) {
                    for (var key in add.data) {
                        params += `${key}=${add.data[key]}&`;
                    }

                    params = params.slice(0, -1);

                    add.url += `?${params}`;
                };

                //xhr.open(请求方式, 请求接口地址, 是否异步)
                xhr.open(add.type, add.url, true);

                //设置响应内容类型
                xhr.responseType = 'json';

                //如果post请求, 需要设置请求头
                if (add.type === 'post') {
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;chatset=utf-8');
                }

                //4、发起http请求
                xhr.send(add.type === 'post' ? params : null);
            })
        };

        ajax({
            //请求方式get、post
            type: 'get',

            //请求地址
            url: 'http://api.tianapi.com/txapi/ncov/index',

            //请求数据
            data: {
                //密钥
                key: '50a5a4225eac60bde85bf361db432457',
            }

        }).then(result => {
            console.log('result ==> ', result);
        });


    </script>
</body>

</html>